
<?php

/**
 * Created by PhpStorm.
 * User: LP
 * Date: 2018/2/28
 * Time: 16:15
 */
class miuDelivered {
    /**
     * 申请补货
     * @param $ids		申请补货的id	多个用逗号拼接
     * @param $counts	申请补货的数量  多个用逗号拼接
     */
    public function applyOutstorage($ids,$counts){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $customer_user_model = M('customer_user');
        $user_role_model = M('customer_user_role');
        $role_model = M('role');
        $orderDeliver_tab = M('module_product_order_deliver');
        $outstorage_tab = M('vendor_outstorage');
        $outstorageDetail_tab = M('vendor_outstorage_detail');
        $depot_tab = M('depot');
        Session::switchCustomer($cid);
        $user_tab = M('user');
        //查询补货人的信息
        $userInfo = $user_tab->where(['id' => $uid])->find();
        $ids = explode(',',$ids);
        $counts = explode(',',$counts);

        $vid = $orderDeliver_tab->where(['id' => $ids[0]])->getField('vid');

        $outstorage_tab->startTrans();
        $data['sponsorId'] = $uid;
        $data['sponsorName'] = $userInfo['fullName'];
        $data['cid'] = $cid;
        $data['sponsorTime'] = date("Y-m-d H:i:s");
        $data['status'] = 'requested';
        $data['type'] = 'allocation';
        $data['deleted'] = 0;
        $data['outstorageNumber'] = $cid .date("YmdHis").$uid;
        $data['vid'] = $vid;

        //匹配发货的仓库
        $where['province'] = array("like","%{$userInfo['province']}%");
        $where['city'] = array("like","%{$userInfo['city']}%");
        $where['cid'] = $cid;
        $where['country'] = $userInfo['county'];
        $depotInfo = $depot_tab->where($where)->select();
        if(count($depotInfo) > 1){
            $data['depotId'] = '';
            $data['depotName'] = '';
        }else if(count($depotInfo) == 1){
            $data['depotId'] = $depotInfo[0]['id'];
            $data['depotName'] = $depotInfo[0]['name'];
            $data['vid'] = $depotInfo[0]['vid'];
        }else{
            $data['depotId'] = '';
            $data['depotName'] = '';
        }

        //添加补货单
        if(!empty($data['depotId'])){

        }
        $outstorageId = $outstorage_tab->add($data);

        foreach($ids as $k=>$v){
            $orderDeliverInfo = $orderDeliver_tab->where(['id' => $v])->find();
            if($counts[$k] <= $orderDeliverInfo['count']){
                //减少需要补货数量
                $orderDeliver_tab->where(['id' => $v])->setDec('count',$counts[$k]);
                $dataDetail[$k]['productName'] = $orderDeliverInfo['productName'];
                $dataDetail[$k]['productUrl'] = $orderDeliverInfo['productUrl'];
                $dataDetail[$k]['pid'] = $orderDeliverInfo['pid'];
                $dataDetail[$k]['cid'] = $cid;
                $dataDetail[$k]['outstorageId'] = $outstorageId;
                $dataDetail[$k]['firstSpecificName'] = $orderDeliverInfo['firstSpecificName'];
                $dataDetail[$k]['secSpecificName'] = $orderDeliverInfo['secSpecificName'];
                $dataDetail[$k]['unitNumber'] = $counts[$k];
                $dataDetail[$k]['miunitNumber'] = $counts[$k];
                $dataDetail[$k]['type'] = $orderDeliverInfo['type'];
            }else{
                Output::instance()->object([
                    'code'=>1,
                    'msg'=>'申请补货失败，补货商品数量大于卖出商品实际数量'
                ]);
            }
        }
        //生成补货的详情
        $outstorageDetailId = $outstorageDetail_tab->addAll($dataDetail);
        if($outstorageDetailId && $outstorageId){
            $outstorage_tab->commit();
            Output::instance()->object([
                'code'=>0,
                'msg'=>'申请补货成功'
            ]);
            //发送站内消息
//            $roleId = $role_model->where(['cid' => $cid, 'englishRole' => 'operationCenterAdmin'])->getField('id');
//            $receiveIds = $user_role_model->alias('r')
//                ->join('wx_customer_user u on u.id = r.userId')
//                ->where(['r.cid' => $cid, 'r.roleId' => $roleId, 'u.vid' => $vid])
//                ->getField('r.userId', true);//接收人id集合数组
//            $receiveIds = array_unique($receiveIds);
            $receiveIds = $customer_user_model->where(['customerId' => $cid, 'vid' => $vid])->getField('id', true);
            $message = '<p>好友发起了新的补货申请，请前往订单出库模块查看，<a href = "#/joymap/depot/channel/outDepot">前往查看</a></p>';
            PlatMessageAction::pushMessage('好友补货申请提醒', $message, $receiveIds, '', 0, 'newAllocation', '订单出库', 2, 1, 0, 0, $message, $cid);
        }else{
            $outstorage_tab->rollback();
            Output::instance()->object([
                'code'=>1,
                'msg'=>'申请补货失败'
            ]);
        }
    }

    /**
     * 待补货列表
     * @param null $keyword 搜索关键字
     */
    public function waitApplyOutstorageList($keyword = null,$start = 0, $limit = 10){
        $cid = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $orderDeliver_tab = M('module_product_order_deliver');
        Session::switchCustomer($cid);
        $where['cid'] = array('eq', $cid);
        $where['uid'] = array('eq', $uid);
        $where['count'] = array('gt', 0);
        empty($keyword) ? '' : $where['productName'] = array("like","%{$keyword}%");
        $productData = $orderDeliver_tab->where($where)->limit($start,$limit)->select();
        $total = $orderDeliver_tab->where($where)->count();
        Output::instance()->object([
            'code'=>0,
            'msg'=>'获取列表成功',
            'data'=>$productData,
            'total'=>$total
        ]);
    }

    /**
     * 申请补货记录
     * @param $status					状态
     * @param null $outstorageNumber	补货单号
     */
    public function applyOutstorageRecord($status,$outstorageNumber = null,$start,$limit){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        $uid = Session::$user['userId'];
        Session::switchCustomer(0);
        $outstorage_tab = M('vendor_outstorage');
        $outstorageDetail_tab = M('vendor_outstorage_detail');
        Session::switchCustomer($cid);
        $where['status'] = array('eq', $status);
        $where['sponsorId'] = array('eq', $uid);
        empty($outstorageNumber) ? '' : $where['outstorageNumber'] = array("like","%{$outstorageNumber}%");
        $data = $outstorage_tab->where($where)->field('id,status,outstorageNumber,sponsorTime')->order('sponsorTime desc')->limit($start,$limit)->select();
        $count = $outstorage_tab->where($where)->count();
        foreach($data as $k=>$v){
            $detail = $outstorageDetail_tab->where(['outstorageId' => $v['id']])->field('pid,productName,productUrl,firstSpecificName,secSpecificName,miunitNumber,unitNumber,type')->select();
            $data[$k]['list'] = $detail;
        }

        Output::instance()->object([
            'code'=>0,
            'msg'=>'获取列表成功',
            'data'=>$data,
            'total'=>$count
        ]);
    }

    /**
     * 发货订单列表
     * @param $qId      营销圈id
     * @param $type     类型
     * @param $start    开始条数
     * @param $limit    每页条数
     * @param int $status   状态
     * @param null $search  查询关键字
     */
    public function getDeliverOrderList($qId, $type, $start, $limit, $status = 0, $search = null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderDte_table = M('module_product_order_detail');
        Session::switchCustomer($customerId);
        $order = "a.createTime desc";
        $pageStart = $start * $limit;
        $where["a.qId"] = array('eq', $qId);
        $where["a.deleted"] = array('eq', 0);
        $search ? $where["a.serialNumber"] = array("like", "%" . $search . "%") : "";
        $where['a.type'] = ['neq', ORDER_TYPE_FORM];
        $where['a.deliverMiUId'] = array('eq', $uId);
        switch ($status) {
            case 0:
                $where["a.status"] = array("eq", 'teaming');
                break;
            case 1:
                $where["a.status"] = array(array("eq", order_status_delivering), array("eq", order_status_deliveringtostore), array("eq", order_status_ordersign), array("eq", "supported"), "or");
                break;
            case 2:
                $where["a.status"] = array(array("eq", order_status_delivered), array("eq", order_status_deliveredtostore), "or");
                break;
            case 3:
                $where["a.status"] = array(array("eq", order_status_ok), array("eq", order_status_confirmsign), 'or');
                break;
            case 4:
                $where["_string"] = "a.status='" . order_status_refund . "' or a.status='" . ORDER_STATUS_REFUNDEDPART . "' or a.status='" . ORDER_STATUS_REFUNDING . "'";
                break;
            case 5: //已取消
                $where["a.status"] = order_status_cancel;
                break;
        }
        $orderList = $orderModel->alias("a")
            ->join("inner join wx_module_product_order_detail b on a.id =b.oid")
            ->where($where)
            ->field("a.*")
            ->order($order)
            ->group("a.id")
            ->limit($pageStart, $limit)
            ->select();
        Log::write('jie--order'.$orderModel->getLastSql());
        $count = $orderModel->alias("a")
            ->join("inner join wx_module_product_order_detail b on a.id =b.oid")
            ->where($where)
            ->order($order)
            ->count("a.id");

        foreach ($orderList as $key => $val) {
            $orderDet = $orderDte_table->where(['oid'=>$val['id']])->field('pid,name, picUrl, picUrl1, price')->select();
            $orderList[$key]["productList"] = $orderDet;
        }

        Session::switchCustomer($customerId);
        $order = new StdClass();
        $order->count = $count;
        $order->pageCount = getPageCount($count, $limit);
        Log::write('jie--order-3'.print_r($order, true));
        $order->orderList = $orderList;
        $order->uType = $type;
        $order->uId = $uId;
        Output::instance()->object($order);
    }

    /**
     * 快递列表
     */
    public function expressList(){
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0); 
        $expressModel = M("module_express");
        Session::switchCustomer($cid);
        $expressList = $expressModel->select();
        Output::instance()->object($expressList);
    }

    /**
     * 确认出库单
     * @param $id 出库单id
     */
    public function confirmOutstorage($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $vendorOutstorage = M('vendor_outstorage');
        $vendorOutstorageDetail = M("vendor_outstorage_detail");
        $OutstorageDetailMatch = M("vendor_outstorage_detail_match");
        $vendorStockModel = M("vendor_stock");
        $accountVendor = M("account_vendor");
        $mivendor = M("mivendor");
        Session::switchCustomer($customerId);
        $time = date("Y-m-d H:i:s");;

        //修改出库单状态
        $vendorOutstorage->startTrans();
        $status_result = $vendorOutstorage->where(['id' => $id])->setField('status', 'confirm');
        $status_result = $vendorOutstorage->where(['id' => $id])->setField('confirmTime', $time);

        //取仓库id
        $vendorOutstorageInfo = $vendorOutstorage->where(['id' => $id])->find();

        //出库单详细商品信息查询
        $detailInfo = $vendorOutstorageDetail->where("outstorageId=$id")->select();
        foreach ($detailInfo as $key=>$value) {
            if($value['type'] == 'point'){
                continue;
            }
            //进行此商品库存量查询
            $where['cid'] = $customerId;
            $where['depotId'] = $vendorOutstorageInfo['depotId'];
            $where['pid'] = $value['pid'];
            empty($value['firstSpecificName']) ? '' : $where['firstSpecificName'] = $value['firstSpecificName'];
            empty($value['secSpecificName']) ? '' : $where['secSpecificName'] = $value['secSpecificName'];
            $depotInfo = $vendorStockModel->field('totalNumber')->where($where)->find();
            //库存总量减少，以及时间的修改
            $save_depot_info['totalNumber'] = $depotInfo['totalNumber'] - $value['miunitNumber'];
            $save_depot_info['updateTime'] = $time;
            $save_stock = $vendorStockModel->where($where)->save($save_depot_info);

            $totalValue = $OutstorageDetailMatch->where(['outstorageId' => $vendorOutstorageInfo['id'],'pid' => $value['pid']])->sum('totalValue');

            //供应商增加收入与收入记录
//            $accountResult = self::vendorAddIn($vendorOutstorageInfo['vid'],'depot',$vendorOutstorageInfo['id'],$vendorOutstorageInfo['serialNumber'],$value['productName'],$totalValue);

            $data = null;
            $data['module'] = 'depot';
            $data['type']=0;
            $data['deleted']=0;
            $data['createTime']=$time;
            $data['vId']= $vendorOutstorageInfo['vid'];
            $data['moduleId']=$vendorOutstorageInfo['id'];
            $data['description'] = $value['productName'];
            $data['serialNumber'] = $vendorOutstorageInfo['outstorageNumber'];

            $depotRevenueSetting = $mivendor->where(['id' => $vendorOutstorageInfo['vid']])->getField('depotRevenueSetting');
            $totalValue = $data['money']=$totalValue*($depotRevenueSetting/100);
            $accountResult = $accountVendor->add($data);

            $query = "UPDATE wx_mivendor SET totalRevenue = totalRevenue + $totalValue,balance=balance+$totalValue WHERE id =".$vendorOutstorageInfo['vid'];
            $result = $mivendor->query($query);

            if (!is_numeric($save_stock) && $accountResult && $result) {
                $vendorOutstorage->rollback();
                $return['code'] = 1;
                $return['msg'] = '确认失败，请重试';
                Output::instance()->object($return);
                exit();
            }

        }
        $vendorOutstorage->commit();
        /** 5. 返回结果 */
        $return['code'] = 0;
        $return['msg'] = '确认成功';
        Output::instance()->object($return);

    }

    /**
     * 待补货数量
     */
    public function waitApplyOutstorageNum($qId){
        $customerId = Session::$user['customerId'];
        $uId = Session::$user['userId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);

        $where["a.qId"] = array('eq', $qId);
        $where["a.deleted"] = array('eq', 0);
        $where['a.type'] = ['neq', ORDER_TYPE_FORM];
        $where['a.deliverMiUId'] = array('eq', $uId);
        $where["a.status"] = array(array("eq", order_status_delivering), array("eq", order_status_deliveringtostore), array("eq", order_status_ordersign), array("eq", "supported"), "or");

        $count = $orderModel->alias("a")
            ->join("inner join wx_module_product_order_detail b on a.id =b.oid")
            ->where($where)
            ->count("a.id");

//        $cid = Session::$user['customerId'];
//        $uid = Session::$user['userId'];
//        Session::switchCustomer(0);
//        $orderDeliver_tab = M('module_product_order_deliver');
//        Session::switchCustomer($cid);
//        $where['cid'] = array('eq', $cid);
//        $where['uid'] = array('eq', $uid);
//        $num = $orderDeliver_tab->where($where)->sum('count');

        Output::instance()->object([
            'code'=>0,
            'msg'=>'确认成功',
            'num'=>$count
        ]);
    }


    public function vendorAddIn($vid,$module,$moduleId,$serialNumber,$description,$totalValue){

        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $accountVendor = M("account_vendor");
        $mivendor = M("mivendor");
        $vendorOutstorage = M('vendor_outstorage');
        Session::switchCustomer($customerId);
        $data = null;
        $data['module'] = $module;
        $data['type']=0;
        $data['deleted']=0;
        $data['createTime']=date("Y-m-d H:i:s");
        $data['oId']='';
        $data['vId']= $vid;
        $data['moduleId']=$moduleId;
        $data['description'] = $description;
        $data['serialNumber'] = $serialNumber;

        $depotRevenueSetting = $mivendor->where(['id' => $vid])->getField('depotRevenueSetting');
        $totalValue = $data['money']=$totalValue*($depotRevenueSetting/100);
        $accountResult = $accountVendor->add($data);

        $query = "UPDATE wx_vendor_agent SET totalRevenue = totalRevenue + $totalValue,balance=balance+$totalValue WHERE id =".$vid;
        $result = $mivendor->query($query);
        if($accountResult && $result){
            return true;
        }else{
            $vendorOutstorage->rollback();
            return false;
        }
    }

}